<template>
  <el-dialog draggable :title="dialog.title" v-model="dialog.isShowDialog" width="35%" :close-on-click-modal="false" destroy-on-close>
    <el-form ref="FormRef" :model="userForm" :rules="rules" label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="userForm.username" placeholder="请输入账户名称" clearable :maxlength="20" :prefix-icon="User">
          <template #append>
            <el-tooltip content="用户名长度3-20个字符" placement="top">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model.trim="userForm.name" placeholder="请输入用户昵称" clearable :maxlength="20" :prefix-icon="UserFilled" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model.trim="userForm.email" placeholder="请输入邮箱地址" clearable :prefix-icon="Message" />
      </el-form-item>

      <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="userForm.roleIds"
          multiple
          placeholder="请选择角色"
          clearable
          collapse-tags
          collapse-tags-tooltip
          :prefix-icon="Collection"
        >
          <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
            <span class="role-option">
              <el-icon><UserFilled /></el-icon>
              {{ item.roleName }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="用户描述" prop="remark">
        <el-input
          v-model="userForm.remark"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 6 }"
          placeholder="请输入用户描述"
          maxlength="150"
          show-word-limit
          resize="none"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCancel" plain>取 消</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmit(FormRef)">
          {{ dialog.submitTxt }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="editUser">
  import { ref, reactive } from 'vue';
  import { useRoleApi } from '@/api/role-api.js';
  import { useUserApi } from '@/api/user-api.js';
  import { DialogType, RStatus } from '@/common/comstants.js';
  import { User, UserFilled, Message, Collection, InfoFilled } from '@element-plus/icons-vue';

  const userInitInfo = {
    username: '',
    name: '',
    email: '',
    roleIds: [],
    remark: '',
  };

  const userForm = ref(userInitInfo);
  const _emit = defineEmits(['refresh']);
  const FormRef = ref();
  const loading = ref(false);
  const roleList = ref([]);

  const dialog = ref({
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  });

  const rules = {
    username: [
      { required: true, message: '请输入用户名称', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    ],
    name: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    ],
  };

  const openDialog = (type = DialogType.ADD, row) => {
    getRoleList();
    dialog.value.isShowDialog = true;
    dialog.value.type = type;

    if (type === DialogType.EDIT) {
      userForm.value = { ...row };
      userForm.value.roleIds = row.userRoles.map((item) => item.role.roleId);
      dialog.value.title = '修改用户';
      dialog.value.submitTxt = '修 改';
      return;
    }

    dialog.value.title = '新增用户';
    dialog.value.submitTxt = '新 增';
    userForm.value = { ...userInitInfo };
  };

  const closeDialog = () => {
    dialog.value.isShowDialog = false;
  };

  const onCancel = () => {
    closeDialog();
  };

  const onSubmit = async (formEl) => {
    if (!formEl) return;
    await formEl.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          const operationPromise =
            dialog.value.type === DialogType.ADD ? useUserApi().addUser(userForm.value) : useUserApi().updateUser(userForm.value);

          const res = await operationPromise;
          if (res.status === RStatus.SUCCESS) {
            ElMessage.success(res.message);
            _emit('refresh');
            closeDialog();
          }
        } finally {
          loading.value = false;
        }
      }
    });
  };

  const getRoleList = async () => {
    const res = await useRoleApi().getAllRole();
    if (res.status === RStatus.SUCCESS) {
      roleList.value = res.data;
    }
  };

  defineExpose({ openDialog });
</script>

<style lang="scss" scoped>
  .role-option {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      color: #4a90e2;
    }
  }
</style>
@/api/role-api@/api/user-api